<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;


/**
 * 用户绿色积分转换消费积分
 */
class ConvertConsumptionPoints extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('convert_consumption_points')->setDescription('绿色积分转为消费积分');
    }

    protected function execute(Input $input, Output $output)
    {
        //每次绿色积分转换百分比
        $writeoff_points = Db::name('config')->where('config_key','writeoff_points')->value('config_content');

        if($writeoff_points > 0 && $writeoff_points < 1){
            //获取绿色积分不为零的数据进行转换
            $list = Db::name('user')->where('green_scores', '>',0)->select();

            foreach ($list as $value) {
                $day_time = strtotime(date('Y-m-d'));
                $count = Db::name('detailed_integral')->where('user_id',$value['id'])->where('create_time','>',$day_time)->count();

                if($count > 0){
                    continue;
                }

                $green_scores_before = $value['green_scores'];
                $green_scores_amount = bcmul($green_scores_before,$writeoff_points,2);
                $green_scores_after = bcsub($green_scores_before,$green_scores_amount,2);

                $integral_before = $value['integral'];
                $integral_amount = $green_scores_amount;
                $integral_after = bcadd($integral_before,$integral_amount,2);

                Db::name('user')
                    ->where('id', $value['id'])
                    ->update([
                        'integral' => $integral_after,
                        'green_scores' => $green_scores_after
                    ]);

                Db::name('detailed_integral')->insert([
                    'user_id' => $value['id'],
                    'type' => 7,
                    'before' => $integral_before,
                    'amount' => $integral_amount,
                    'after' => $integral_after,
                    'related_uid' => 0,
                    'order_sn' => '',
                    'remark' => '绿色积分转消费积分',
                    'create_time' => time()
                ]);

                Db::name('detailed_green_scores')->insert([
                    'user_id' => $value['id'],
                    'type' => 103,
                    'before' => $green_scores_before,
                    'amount' => $green_scores_amount,
                    'after' => $green_scores_after,
                    'related_uid' => 0,
                    'order_sn' => '',
                    'remark' => '绿色积分转消费积分',
                    'create_time' => time()
                ]);
            }
        }
        $output->writeln('绿色积分转为消费积分');
    }
}
